

/**
 * Ajax方法
 */

Mao.Ajax = {
	//发出ajax请求
	request:function(cfg){
		if(typeof cfg.url=="undefined"){return false;}//URL必填
		if(typeof cfg.unsyn!=="boolean"){cfg.unsyn=true}//默认异步请求
		var req = this.getRequest();//初始化xhr对象
		cfg.method = cfg.method||"GET";//默认GET请求
		var isPost = cfg.method.toUpperCase()=="POST";//是否POST方法
		var p = encodeParams(cfg);
		req.open(cfg.method, cfg.url+(isPost||!cfg.hasParams ? "": "?"+p), cfg.unsyn);
		if(isPost){req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");}
		req.send(isPost ? p : null);
		if(cfg.unsyn){//异步请求
			req.onreadystatechange = function(){
				if(req.readyState==4){
					cfg.success.call(req);
					//console.debug(this);
				}
			}
		}else{//同步请求
			cfg.success.call(req);
		}
		
		//参数编码
		function encodeParams(cfg){
			var r = [];
			for(var i in cfg.params){
				r.push(i+"="+cfg.params[i]);
			}
			cfg.hasParams = r,length>0;
			return r.join("&");
		}
	},
	//跨浏览器获取XMLHttpRequest
	getRequest: function(){
		var _x;
		if(typeof XMLHttpRequest=="function"){
			_x = new XMLHttpRequest();
		}else{
			try{ _x =  new ActiveXObject("Msxml2.XMLHTTP");}catch(e){
				try { _x = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
					throw("XXX", "什么烂浏览器，Ajax也不支持，BS！");
				} 
			}
		}
		return _x;
	}
}